package com.mengchengnet.chaperonage.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.mengchengnet.chaperonage.BaseActivity;
import com.mengchengnet.chaperonage.R;
import com.mengchengnet.chaperonage.adapter.AddressAdapter;
import com.mengchengnet.chaperonage.domain.base.Address;
import com.mengchengnet.chaperonage.util.PreferenceUtil;
import com.mengchengnet.chaperonage.util.Url;
import com.mengchengnet.chaperonage.view.refreshableListView.RefreshableListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/8/23.
 */

public class AddressActivity extends BaseActivity {
    private ImageView iv;
    private RefreshableListView listView;
    private ArrayList<Address> list;
    private AddressAdapter adapter;
    private int checkNum; // 记录选中的条目数量
    private RequestQueue requestQueue;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            adapter=new AddressAdapter(AddressActivity.this,list);
            listView.setAdapter(adapter);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address);
        toolbarState=TOOLBAR_STYLE_ADDADDRESS;
        initToolbar("陪护地址");
        initView();


    }

    private void initView() {
        requestQueue= Volley.newRequestQueue(getApplication());
        iv= (ImageView) findViewById(R.id.toolbar_iv_icon);
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent =new Intent();
                intent.setClass(AddressActivity.this,SelectAddressActivity.class);
                startActivityForResult(intent,1);
            }
        });
        listView= (RefreshableListView) findViewById(R.id.addressList);
        list=new ArrayList<>();

        get();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                for (Address add:list){
                    add.setChecked(false);
                }
              list.get(i-1).setChecked(true);
                adapter.notifyDataSetChanged();
                Intent intent =new Intent();
                intent.putExtra("name", list.get(i-1).getName());
                AddressActivity.this.setResult(RESULT_OK,intent);
                AddressActivity.this.finish();


            }
        });


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK){
            Log.e("地址列表页", "onActivityResult: "+data.getStringExtra("name") );
            String name=data.getStringExtra("name");
            String relationship=data.getStringExtra("relationship");
            String address=data.getStringExtra("address");
            String phone=data.getStringExtra("phone");
            String others=data.getStringExtra("others");
            Address dress=new Address();
            dress.setRelationship(relationship);
            dress.setName(name);
            dress.setAddress(address);
            dress.setPhone(phone);
            dress.setOthers(others);
            list.add(dress);
            adapter=new AddressAdapter(AddressActivity.this,list);
            listView.setAdapter(adapter);


        }

    }


    private void get(){
        StringRequest request = new StringRequest(Request.Method.POST, Url.getUserInfo,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        Log.e("getList", "getList接口返回值："+result );
                        JSONObject jsonObject;
                        try {
                            if(result != null && result.startsWith("\ufeff"))
                            {
                                result =  result.substring(1);
                            }
                            jsonObject = new JSONObject(result);
                            if (jsonObject.getString("code").equals("00")){
                                JSONArray array=jsonObject.getJSONArray("careList");
                                for (int i = 0; i <array.length() ; i++) {
                                    JSONObject obj=array.getJSONObject(i);
                                    String name=obj.getString("name");
                                    String relationShip=obj.getString("relationShip");
                                    String address=obj.getString("address");
                                    String phone=obj.getString("phone");
                                    String remarks=obj.getString("remarks");
                                    Address dress=new Address();
                                    dress.setRelationship(relationShip);
                                    dress.setName(name);
                                    dress.setAddress(address);
                                    dress.setPhone(phone);
                                    dress.setOthers(remarks);
                                    list.add(dress);
                                }
                                   handler.sendEmptyMessage(0);
                            }
                            else {
                                Toast.makeText(AddressActivity.this, "失败", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                Toast.makeText(AddressActivity.this, "网络异常请稍后重试！", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("version", PreferenceUtil.getString(getApplication(),"versionCode"));
                map.put("loginId", PreferenceUtil.getString(getApplication(),"userId"));
                return map;
            }
        };
        request.setTag("GetFenZu");
        request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, // 默认超时时间，应设置一个稍微大点儿的
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, // 默认最大尝试次数
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(request);

    }
}
